package cn.iocoder.yudao.module.infra.controller.admin.oss;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.io.FileUtils;
import cn.iocoder.yudao.module.infra.controller.admin.oss.vo.OssPageReqVO;
import cn.iocoder.yudao.module.infra.dal.dataobject.oss.OssDO;
import cn.iocoder.yudao.module.infra.service.oss.OssService;
import com.aliyun.oss.ServiceException;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Api(tags = "OSS - 文件存储")
@RestController
@RequestMapping("/infra/oss")
@Validated
@Slf4j
public class OssController {

    @Resource
    OssService ossService;

    /**
     * 上传OSS对象存储
     */
    @ApiOperation("上传OSS对象存储")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", paramType = "query", dataTypeClass = File.class, required = true)
    })
    @PostMapping("/upload")
    public CommonResult<Map<String, String>> upload(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            throw new ServiceException("上传文件不能为空");
        }
        OssDO oss = ossService.upload(file);
        Map<String, String> map = new HashMap<>(2);
        map.put("id", oss.getId().toString());
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getFileName());
        map.put("originalName", oss.getOriginalName());
        return success(map);
    }
    @PostMapping("/uploadBase64")
    public CommonResult<Map<String, String>> upload(@RequestParam("ImageData") String ImageData) {

        if (ObjectUtil.isNull(ImageData)) {
            throw new ServiceException("上传文件不能为空");
        }
        OssDO oss = ossService.upload(ImageData);

        Map<String, String> map = new HashMap<>(2);
        map.put("id", oss.getId().toString());
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getFileName());
        map.put("originalName", oss.getOriginalName());
        return success(map);
    }



    @ApiOperation("下载OSS对象存储")
    @GetMapping("/download/{id}")
    public void download(@ApiParam("OSS对象ID") @PathVariable Long id, HttpServletResponse response) throws IOException {
        OssDO ossDO = ossService.getById(id);
        if (ObjectUtil.isNull(ossDO)) {
            throw new ServiceException("文件数据不存在!");
        }
        response.reset();
        FileUtils.setAttachmentResponseHeader(response, ossDO.getOriginalName());
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE + "; charset=UTF-8");
        long data;
        try {
            data = HttpUtil.download(ossDO.getUrl(), response.getOutputStream(), false);
        } catch (HttpException e) {
            if (e.getMessage().contains("403")) {
                throw new ServiceException("无读取权限, 请在对应的OSS开启'公有读'权限!");
            } else {
                throw new ServiceException(e.getMessage());
            }
        }
        response.setContentLength(Convert.toInt(data));
    }

    @GetMapping("/page")
    @ApiOperation("获得oss分页")
    //@PreAuthorize("@ss.hasPermission('infra:file:query')")
    public CommonResult<PageResult<OssDO>> getFilePage(@Valid OssPageReqVO pageVO) {
        PageResult<OssDO> pageResult = ossService.getFilePage(pageVO);
        return success(pageResult);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除文件")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = Long.class)
    //@PreAuthorize("@ss.hasPermission('infra:file:delete')")
    public CommonResult<Boolean> deleteFile(@RequestParam("ids") Collection<Long> ids) {
        ossService.deleteFile(ids);
        return success(true);
    }
}
